<template>
  <view class="review-page">
    <view class="goods-list">
      <view
        v-for="item in orderItems"
        :key="item.productId"
        class="goods-item"
        :class="{ reviewed: item.reviewed }"
      >
        <image :src="item.productImage" class="product-image" mode="aspectFill" />
        <view class="product-info">
          <text class="product-name">{{ item.productName }}</text>
          <view class="rating-section">
            <text>评分：</text>
            <view class="stars">
              <text
                v-for="star in 5"
                :key="star"
                class="star"
                :class="{ active: star <= (item.grade || 0) }"
                @tap="setGrade(item, star)"
              >
                ★
              </text>
            </view>
          </view>
          <textarea
            v-model="item.content"
            placeholder="请输入您的评价（选填）"
            :disabled="item.reviewed"
            class="review-textarea"
          />
          <button
            size="mini"
            type="primary"
            :disabled="item.reviewed || !item.grade"
            @tap="submitReview(item)"
            class="submit-btn"
          >
            {{ item.reviewed ? '已评价' : '提交评价' }}
          </button>
        </view>
      </view>
    </view>

    <view v-if="orderItems.length === 0" class="empty-tip">
      暂无商品可评价
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import userManager from '@/common/utils/user.js';
import { getOrderDetail ,addReview } from '@/api/Productapi.js'; // 需要你实现这个 API

const orderId = ref('');

// 商品列表（来自订单详情）
const orderItems = ref([]);

onMounted(async () => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  orderId.value = currentPage.options.orderId;

  if (!orderId.value) {
    uni.showToast({ title: '缺少订单ID', icon: 'none' });
    uni.navigateBack();
    return;
  }

  await loadOrderDetails();
});

// 加载订单详情（获取商品列表）
const loadOrderDetails = async () => {
  const userId = userManager.user.userId;
  if (!userId) {
    uni.showToast({ title: '请先登录', icon: 'none' });
    setTimeout(() => uni.switchTab({ url: '/pages/user/user' }), 1000);
    return;
  }

  uni.showLoading({ title: '加载商品...' });
  try {
    // 调用接口：GET /api/mall/orderDetail/list/{userId}?orderId=xxx
    const data = await getOrderDetail(orderId.value);
    if (data && Array.isArray(data)) {
      // 初始化每项的评价状态（假设后端未返回是否已评，这里默认都未评）
      orderItems.value = data.map(item => ({
        ...item,
        grade: 0,
        description: '',
        reviewed: false // 实际项目应从后端判断是否已评价
      }));
    }
  } catch (err) {
    console.error('加载订单详情失败:', err);
    uni.showToast({ title: '加载失败', icon: 'none' });
  } finally {
    uni.hideLoading();
  }
};

// 设置评分
const setGrade = (item, grade) => {
  if (!item.reviewed) {
    item.grade = grade;
  }
};

// 提交单个商品评价
const submitReview = async (item) => {
  const userId = userManager.user.userId;
  if (!userId) {
    uni.showToast({ title: '请先登录', icon: 'none' });
    return;
  }

  if (!item.grade) {
    uni.showToast({ title: '请选择评分', icon: 'none' });
    return;
  }

  uni.showLoading({ title: '提交中...' });
  try {
	console.log('item:',item);
	const success = await addReview(item.orderId,item.productId, {
      description: item.content || '', 
      grade: item.grade
    });
    if (success) {
      uni.showToast({ title: '评价成功', icon: 'success' });
      item.reviewed = true; // 标记为已评价
    } else {
      uni.showToast({ title: '评价失败', icon: 'none' });
    }
  } catch (err) {
    console.error('评价失败:', err);
    uni.showToast({ title: '网络错误', icon: 'none' });
  } finally {
    uni.hideLoading();
  }
};
</script>

<style scoped>
.review-page {
  padding: 30rpx;
  background-color: #f8f9fa;
}

.goods-item {
  display: flex;
  background: white;
  border-radius: 16rpx;
  padding: 28rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.goods-item:hover {
  transform: translateY(-2rpx);
  box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.12);
}

.goods-item.reviewed {
  opacity: 0.7;
  cursor: not-allowed;
}

.product-image {
  width: 180rpx;
  height: 180rpx;
  border-radius: 12rpx;
  margin-right: 30rpx;
  object-fit: cover;
  border: 1rpx solid #eee;
}

.product-info {
  flex: 1;
}

.product-name {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  line-height: 1.4;
  margin-bottom: 24rpx;
}

.rating-section {
  display: flex;
  align-items: center;
  margin-bottom: 24rpx;
}

.rating-section text {
  font-size: 28rpx;
  color: #666;
  margin-right: 16rpx;
}

.stars {
  display: flex;
  gap: 10rpx;
  font-size: 36rpx;
}

.star {
  color: #ccc;
  cursor: pointer;
  transition: color 0.2s ease;
}

.star.active {
  color: #ffcc00;
}

.review-textarea {
  width: 100%;
  height: 100rpx;
  border: 1rpx solid #ddd;
  border-radius: 12rpx;
  padding: 20rpx;
  font-size: 28rpx;
  color: #333;
  line-height: 1.6;
  background-color: #fff;
  margin-bottom: 20rpx;
  resize: none;
}

.review-textarea::placeholder {
  color: #999;
}

.submit-btn {
  width: 180rpx;
  height: 60rpx;
  font-size: 28rpx;
  border-radius: 30rpx;
  background-color: #007AFF;
  color: white;
  border: none;
  box-shadow: 0 2rpx 8rpx rgba(0, 122, 255, 0.3);
}

.submit-btn:disabled {
  background-color: #cccccc;
  color: #999;
}

.empty-tip {
  text-align: center;
  padding: 100rpx 0;
  color: #999;
  font-size: 28rpx;
}
</style>